package cn.xueden.system.listener;

import cn.xueden.system.converter.UserConverter;
import cn.xueden.system.model.dto.UserImportDTO;
import cn.xueden.system.model.entity.User;
import cn.xueden.system.service.IUserService;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import lombok.Builder;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.List;

/**功能描述：用户导入监听器
 * @author:梁志杰
 * @date:2025/6/10
 * @description:cn.xueden.system.listener
 * @version:1.0
 */
@RequiredArgsConstructor
public class UserImportListener implements ReadListener<UserImportDTO> {

    /**
     * 缓存的数据量
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<User> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    /**
     * 用户服务接口
     */
    private final IUserService userService;

    /**
     * 转换为实体对象
     */
    private final UserConverter  userConverter;
    /**
     * 错误信息
     */
    private final StringBuilder errorMsg = new StringBuilder();
    /**
     * 读取行数
     */
    private int rowNumber = 1;

    /**
     * 读取数据
     * @param data
     * @param context
     */
    @Override
    public void invoke(UserImportDTO data, AnalysisContext context) {
        rowNumber++;
        String validateResult = validateData(data);
        if (StringUtils.isNotBlank(validateResult)) {
            errorMsg.append("第").append(rowNumber).append("行: ").append(validateResult).append("; ");
            return;
        }

        User user = userConverter.userImportDTOToEntity(data);
        // 设置默认密码
        user.setPassword(new BCryptPasswordEncoder().encode("123456"));
        cachedDataList.add(user);

        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }


    /**
     * 所有数据解析完成了 都会来调用
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
    }

    /**
     * 检验数据
     * @param data
     * @return
     */
    private String validateData(UserImportDTO data) {
        if (StringUtils.isBlank(data.getUserName())) {
            return "用户名不能为空";
        }
        if (userService.existsByUserName(data.getUserName())) {
            return "用户名已存在";
        }
        if (data.getRoleId() == null) {
            return "角色ID不能为空";
        }
        return "";
    }

    /**
     * 保存数据
     */
    private void saveData() {
        if (!cachedDataList.isEmpty()) {
            userService.saveBatchImportData(cachedDataList);
        }
    }

    public String getErrorMsg() {
        return errorMsg.toString();
    }

    public boolean hasError() {
        return errorMsg.length() > 0;
    }
}
